/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.openjawtech.xscraper.scraper.runtime.scripting;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.Bindings;
import com.openjawtech.xscraper.scraper.exception.ScrapeException;
import java.util.ArrayList;
import java.util.List;
import sun.org.mozilla.javascript.internal.NativeArray;

/**
 *
 * @Created on 17-Apr-2009, 18:59:56
 * @author Wenbo.Sun
 */
public class JSScripting {

    private ScriptEngine scriptEngine;

    public JSScripting() {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        scriptEngine = engineManager.getEngineByExtension("js");
    }

    public Object eval(String script) throws ScrapeException {
        Object object = null;
        try {
            object = scriptEngine.eval(script);
        } catch (Throwable t) {
            throw new ScrapeException("eval the script failed", t);
        }
        return object;
    }

    public Object eval(String script, Bindings bindings) throws ScrapeException {
        Object object = null;
        try {
            object = scriptEngine.eval(script, bindings);
        } catch (Throwable t) {
            throw new ScrapeException("eval the script failed", t);
        }
        return object;
    }

    public Object getValue(String key, String script) throws ScrapeException {
        Object object = null;
        try {
            scriptEngine.eval(script);
            object = scriptEngine.get(key);
        } catch (Throwable t) {
            throw new ScrapeException("get value from script failed", t);
        }
        return object;
    }

    public Object getValue(String key, String script, Bindings bindings) throws ScrapeException {
        Object object = null;
        try {
            scriptEngine.eval(script, bindings);
            object = scriptEngine.get(key);
        } catch (Throwable t) {
            throw new ScrapeException("get value from script failed", t);
        }
        return object;
    }

    public List<String> getArrayValue(String key, String script) {
        NativeArray array = (NativeArray) getValue(key, script);
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < array.getLength(); i++) {
            list.add((String) array.get(i, array));
        }
        return list;
    }
}
